<template>
  <el-form
    ref="formRef"
    label-width="100px"
    class="addForm"
    style="margin-top: 20px"
    :rules="formRules"
    :model="formData"
  >
    <el-form-item v-if="picture" label="用户头像">
      <el-upload
        class="avatar-uploader"
        ref="uploadRef"
        :limit="1"
        :show-file-list="false"
        :accept="imageType.concat(',').toString()"
        :http-request="uploadChange"
        :before-upload="beforeUpload"
        :on-success="uploadSuccess"
        :on-errors="uploadErrors"
      >
        <template #default>
          <img
            v-if="formData.picture"
            class="avatar"
            :src="formData.picture as string"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </template>
        <template #tip>
          <div>
            <el-text type="primary">
              提示：图片类型只能是png/jpeg/webp/bmp/gif格式且大小不能超过5MB。
            </el-text>
          </div>
        </template>
      </el-upload>
    </el-form-item>
    <el-form-item label="用户名" prop="userName">
      <el-input
        v-model="formData.userName"
        :disabled="disabledUserName"
        placeholder="用户名由系统自动生成"
      />
    </el-form-item>
    <el-form-item label="真实姓名" prop="realName">
      <el-input v-model="formData.realName" />
    </el-form-item>
    <el-form-item label="用户性别" prop="gender">
      <el-select
        v-model="formData.gender"
        placeholder="搜索类型"
        style="width: 150px"
      >
        <el-option label="未知" :value="0" />
        <el-option label="男" :value="1" />
        <el-option label="女" :value="2" />
      </el-select>
    </el-form-item>
    <el-form-item v-if="grade" label="用户积分" prop="grade">
      <el-input-number v-model="formData.grade" />
    </el-form-item>
    <el-form-item v-if="isAdmin" label="是否管理员" prop="isAdmin">
      <el-switch
        :active-value="1"
        :inactive-value="2"
        v-model="formData.isAdmin"
      />
    </el-form-item>
    <el-form-item label="用户密码" prop="password">
      <el-input
        type="password"
        v-model="formData.password"
        :placeholder="passwordplaceholder"
      />
    </el-form-item>
  </el-form>
</template>
<script setup lang="ts">
import {
  FormInstance,
  FormRules,
  UploadRequestOptions,
  UploadRawFile,
  UploadInstance,
} from "element-plus";
import UserAPI, { type User } from "@/api/user";

const props = defineProps({
  value: {
    type: Object as PropType<User>,
    default: () => {
      return {
        id: 0,
        userName: "",
        realName: "",
        password: "",
        gender: 0,
        grade: 0,
        isAdmin: 0,
        picture: "",
      };
    },
  },
  picture: {
    type: Boolean,
    default: false,
  },
  grade: {
    type: Boolean,
    default: false,
  },
  isAdmin: {
    type: Boolean,
    default: false,
  },
  disabledUserName: {
    type: Boolean,
    default: false,
  },
});

const passwordplaceholder = props.value.id !== 0 ? "不填则不修改密码" : "";

const formRef = ref<FormInstance>();
const formData = ref(props.value);
const formRules = reactive<FormRules<User>>({
  // userName: [
  //   {
  //     required: true,
  //     trigger: "blur",
  //     message: "请输入用户名",
  //   },
  //   {
  //     min: 2,
  //     max: 20,
  //     trigger: "blur",
  //     message: "用户名必须在2-20字符之间",
  //   },
  // ],
  realName: [
    {
      required: true,
      trigger: "blur",
      message: "请输入真实姓名",
    },
    {
      min: 2,
      max: 20,
      trigger: "blur",
      message: "真实姓名必须在2-20字符之间",
    },
  ],
  password: [
    {
      required: formData.value.id === 0 ? true : false,
      trigger: "blur",
      message: "请输入密码",
    },
    {
      min: 10,
      max: 16,
      trigger: "blur",
      message: "密码必须在10-16字符之间",
    },
  ],
  // gender: {},
  // grade: {},
  // isAdmin: {},
});

//头像上传
const uploadRef = ref<UploadInstance>();
const imageType = [
  "image/png",
  "image/jpeg",
  "image/webp",
  "image/bmp",
  "image/gif",
];
const uploadChange = ({ file }: UploadRequestOptions) => {
  return UserAPI.upload(file);
};
const beforeUpload = (rawFile: UploadRawFile) => {
  const isImageSize = rawFile.size / 1024 / 1024 < 5;
  const isImageType = imageType.includes(rawFile.type);
  if (!isImageType) {
    ElMessage.info("您上传的文件不是图片");
  } else if (!isImageSize) {
    ElMessage.info("图片大小不能超过5MB");
  }
  return isImageSize && isImageType;
};
const uploadSuccess = (response: string) => {
  formData.value.picture = response;
  uploadRef.value?.clearFiles();
  ElMessage.success("上传用户头像成功");
};
const uploadErrors = (error: Error) => {
  ElMessage.error("上传失败," + error);
};
//添加用户
const addUser = async () => {
  return await formRef.value?.validate(async (valid, fields) => {
    if (!valid) {
      return;
    }
    await UserAPI.addUser(formData.value);
    ElMessage.success("添加用户成功");
  });
};

//修改用户信息
const editUser = () => {
  return new Promise((resolve, reject) => {
    formRef.value?.validate(async (valid, fields) => {
      if (!valid) {
        reject();
        return;
      }
      const data = await UserAPI.editUser(formData.value);
      ElMessage.success("修改信息成功");
      resolve(data);
    });
  });
};

const resetFields = () => {
  formRef.value?.resetFields();
};

defineExpose({
  formRef,
  formData,
  addUser,
  editUser,
  resetFields,
});
</script>

<style scoped>
.avatar-uploader .avatar {
  display: block;
  width: 120px;
  height: 120px;
}
</style>

<style>
.avatar-uploader .el-upload {
  position: relative;
  display: inline-flex;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
</style>
